import {createRouter, createWebHashHistory} from "vue-router";
//登录
import login from "../views/login";
//注册
import register from "../views/register";
//菜单
import page from "../views/page";
//首页
import index from "../views/index";
//用户
import order from "../views/order";
//用户
import user from "../views/user";

const routes = [
    //登录
    {
        path: "/",
        name: "login",
        component: login,
        meta: {
            requireAuth: true,
            title: "用户登录",
        },
    },
    //登录
    {
        path: "/register",
        name: "register",
        component: register,
        meta: {
            requireAuth: true,
            title: "用户注册",
        },
    },
    //菜单
    {
        path: "/page",
        name: "page",
        component: page,
        children: [
            //首页
            {
                path: "/index",
                name: "index",
                component: index,
                meta: {
                    title: "首页",
                },
            },
            //首页
            {
                path: "/order",
                name: "order",
                component: order,
                meta: {
                    title: "订单",
                },
            },
            //用户
            {
                path: "/user",
                name: "user",
                component: user,
                meta: {
                    title: "我的",
                },
            },
        ],
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

//登录拦截
router.beforeEach((to, from, next) => {
    window.document.title =
        to.meta.title == undefined ? "悦跑校园" : to.meta.title;
    if (!to.meta.requireAuth) {
        var token = sessionStorage.getItem("token");
        if (token != null) {
            next();
        } else {
            next({
                name: "login",
            });
        }
    } else {
        next();
    }
});

export default router;
